﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.Collections.ObjectModel;

namespace TPG.SharePoint.Workflow
{
    public class FeatureReceiver
        : SPFeatureReceiver
    {
        delegate void ConfigActionHandler(Collection<SPWebConfigModification> collection,
            SPWebConfigModification item);

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            HandleConfigChange(properties,
                delegate(Collection<SPWebConfigModification> collection,
                    SPWebConfigModification item)
                {
                    collection.Add(item);
                });
        }

        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            HandleConfigChange(properties,
                delegate(Collection<SPWebConfigModification> collection,
                    SPWebConfigModification item)
                {
                    collection.Remove(item);
                });
        }

        public override void FeatureInstalled(SPFeatureReceiverProperties properties)
        {
        }

        public override void FeatureUninstalling(SPFeatureReceiverProperties properties)
        {
        }

        void HandleConfigChange(SPFeatureReceiverProperties properties,
            ConfigActionHandler handler)
        {
            SPSite siteCollection = (SPSite)properties.Feature.Parent;
            SPWebApplication webApp = siteCollection.WebApplication;

            SPWebConfigModification modification = CreateModification(properties);
            handler(webApp.WebConfigModifications, modification);
            webApp.Update();
            webApp.WebService.ApplyWebConfigModifications();
        }

        private static SPWebConfigModification CreateModification(SPFeatureReceiverProperties properties)
        {
            SPWebConfigModification modification = new SPWebConfigModification();
            modification.Name = "SafeControl[@Assembly='TPG.SharePoint.Workflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d3a33f5f62ef53ef'][@Namespace='TPG.SharePoint.Workflow'][@TypeName='*'][@Safe='True']";
            modification.Path = "configuration/SharePoint/SafeControls";
            modification.Owner = "TPG.SharePoint.Workflow";
            modification.Type = SPWebConfigModification.SPWebConfigModificationType.EnsureChildNode;
            modification.Value = @"<SafeControl Assembly=""TPG.SharePoint.Workflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=d3a33f5f62ef53ef"" Namespace=""TPG.SharePoint.Workflow"" TypeName=""*"" Safe=""True"" />";
            return modification;
        }
    }
}
